#import "RadarPulseView.h"

@interface RadarPulseView ()
@property (nonatomic, assign) BOOL isAnimating;
@end

@implementation RadarPulseView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _pulseColor = [UIColor whiteColor];
        _maxRadius = frame.size.width;
        _pulseCount = 3;
        _duration = 1.5f;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)start {
    if (self.isAnimating) return; // 避免重复播放
    self.isAnimating = YES;

    for (int i = 0; i < self.pulseCount; i++) {
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        circleLayer.bounds = CGRectMake(0, 0, self.maxRadius * 2, self.maxRadius * 2);
        circleLayer.position = CGPointMake(CGRectGetWidth(self.bounds)/2, CGRectGetHeight(self.bounds)/2);
        circleLayer.cornerRadius = self.maxRadius;
        circleLayer.borderColor = self.pulseColor.CGColor;
        circleLayer.borderWidth = 40.f;
        circleLayer.opacity = 0.0;
        [self.layer addSublayer:circleLayer];

        CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        scaleAnim.fromValue = @0.0;
        scaleAnim.toValue = @1.0;

        CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
        opacityAnim.fromValue = @1.0;
        opacityAnim.toValue = @0.0;

        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.animations = @[scaleAnim, opacityAnim];
        group.duration = self.duration;
        group.repeatCount = HUGE_VALF;
        group.beginTime = CACurrentMediaTime() + (i * self.duration / self.pulseCount);
        group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

        [circleLayer addAnimation:group forKey:@"radar"];
    }
}

- (void)stop {
    if (!self.isAnimating) return;
    self.isAnimating = NO;

    // 清除所有动画和图层
    [self.layer.sublayers makeObjectsPerformSelector:@selector(removeAllAnimations)];
    [self.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
}

@end
